package com.love.marriage.TecentIm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.love.marriage.TecentIm.config.LocalImConfig;
import com.love.marriage.TecentIm.service.LocalImService;
import com.love.marriage.TecentIm.vo.LocalImChatListVo;
import com.love.marriage.TecentIm.vo.LocalImportAccountVo;
import com.love.marriage.common.constants.RedisConstants;
import com.love.marriage.common.redisKey.LocalImTokenKey;
import com.love.marriage.utils.RedisUtils;
import com.love.marriage.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class LocalImServiceImpl implements LocalImService {

    private final LocalImConfig localImConfig;

    private final RestTemplate restTemplate;

    private final RedisUtils redisUtils;

    @Override
    public String sendMessage(String fromUser, String toUser, String message) throws Exception {
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/chat/message/send";

        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // TODO: 2025/1/11 添加获取token接口
        String authToken = loginLocalIm(fromUser, localImConfig.getDefaultPassword(), localImConfig.getAppId());
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + authToken);
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("talk_mode", 1); // 根据实际需求设置
        requestBody.put("msg_type", 1);  // 根据实际需求设置
        requestBody.put("receiver_id", toUser); // 假设 toUser 是接收者的 ID
        requestBody.put("content", message);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                return "消息发送成功：" + response.get("message");
            } else {
                throw new Exception("消息发送失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    @Override
    public Boolean importImUser(List<LocalImportAccountVo> accountList) throws Exception {
        String accessToken = loginLocalAdmin(null, null);
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/web/app/import";

        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (accessToken != null && !accessToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + accessToken);
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("app_name", "marriage");
        requestBody.put("accounts", accountList);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Map.class
        );

        log.info("结果ddddddddddd", JSONObject.toJSONString(requestEntity));
        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map response = responseEntity.getBody();
            log.info("map", JSONObject.toJSONString(response));
            if (response != null && Objects.equals(response.get("code"), 200)) {
                return true;
            } else {
                throw new Exception("导入用户失败：" + (response != null ? response : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    @Override
    public String loginLocalAdmin(String phone, String password) throws Exception {
        String authToken = redisUtils.get(LocalImTokenKey.localImAdminToken.getPrefix() + RedisConstants.SEGMENTATION + phone);
        if (StringUtils.isNotBlank(authToken)) {
            return authToken;
        }
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/web/auth/login";
        log.info("url llllllllllllllllllllllllllllllllllllll:{}", url);
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("phone", StringUtils.isBlank(phone) ? localImConfig.getAdminPhone() : phone);
        requestBody.put("password", StringUtils.isBlank(password) ? localImConfig.getAdminPassword() : password);

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                // 解析 data 对象
                Object dataObj = response.get("data");
                if (dataObj instanceof Map) {
                    Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                    String accessToken = (String) dataMap.get("access_token");
                    redisUtils.setEx(LocalImTokenKey.localImAdminToken, phone, accessToken, 86000, TimeUnit.SECONDS);
                    return accessToken != null ? accessToken : "登录成功，但未获取到 access_token";
                } else {
                    throw new Exception("响应数据格式错误：data 不是预期的对象");
                }
            } else {
                throw new Exception("登录失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    @Override
    public String findImUserInfo(String fromUserId, String toUserId) throws Exception {
        // 构建带有查询参数的请求URL
        String url = UriComponentsBuilder
                .fromHttpUrl(localImConfig.getUrl() + "/api/chat/friend/search")
                .queryParam("keyword", toUserId)
                .toUriString();

        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String authToken = loginLocalIm(fromUserId, localImConfig.getDefaultPassword(), localImConfig.getAppId());
        // 添加Authorization头，如果authToken存在
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + authToken);
        }

        // 创建不包含请求体的HttpEntity
        HttpEntity<Void> requestEntity = new HttpEntity<>(headers);

        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.GET,
                requestEntity,
                Map.class
        );
        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                if (response != null && Objects.equals(response.get("code"), 200)) {
                    // 解析 data 对象
                    // 解析 data 对象
                    Object dataObj = response.get("data");
                    if (dataObj instanceof Map) {
                        Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                        return null;
                    } else {
                        throw new Exception("响应数据格式错误：data 不是预期的对象");
                    }
                } else {
                    throw new Exception("查询失败：" + (response != null ? response.get("message") : "未知错误"));
                }
            } else {
                throw new Exception("查找失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    public List<Map<String, Object>> getAccountList(Integer appId) throws Exception {
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/web/app/accounts";

        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        String authToken = loginLocalAdmin(null, null);
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + authToken);
        }

        // 构建请求参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (appId != null) {
            builder.queryParam("app_id", appId);
        }

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.GET,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                // 解析 data 对象
                Object dataObj = response.get("data");
                if (dataObj instanceof java.util.List) {
                    // 处理账号列表
                    return (List<Map<String, Object>>) dataObj;
                } else {
                    throw new Exception("响应数据格式错误：data 不是预期的数组");
                }
            } else {
                throw new Exception("获取账号列表失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    public String loginLocalIm(String account, String password, Integer appId) throws Exception {
        String authToken = redisUtils.get(LocalImTokenKey.localImUserToken.getPrefix() + RedisConstants.SEGMENTATION + account);
        if (StringUtils.isNotBlank(authToken)) {
            return authToken;
        }

        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/chat/auth/login";

        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("account", account);
        requestBody.put("password", StringUtils.isNotBlank(password) ? password : localImConfig.getDefaultPassword());
        requestBody.put("app_id", appId != null ? appId : localImConfig.getAppId());

        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

        // 发送POST请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                url,
                HttpMethod.POST,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                // 解析 data 对象
                Object dataObj = response.get("data");
                if (dataObj instanceof Map) {
                    Map<String, Object> dataMap = (Map<String, Object>) dataObj;
                    String accessToken = (String) dataMap.get("access_token");
                    redisUtils.setEx(LocalImTokenKey.localImUserToken, account, accessToken, 86000, TimeUnit.SECONDS);
                    return accessToken != null ? accessToken : "登录成功，但未获取到 access_token";
                } else {
                    throw new Exception("响应数据格式错误：data 不是预期的对象");
                }
            } else {
                throw new Exception("登录失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    @Override
    public Integer getLocalImId(String account) throws Exception {
        List<Map<String, Object>> accountList = getAccountList(localImConfig.getAppId());
        if (account == null || accountList.isEmpty()) {
            return null;
        }
        for (Map<String, Object> accountInfo : accountList) {
            if (account.equals(accountInfo.get("account"))) {
                return (Integer) accountInfo.get("id");
            }
        }
        return null;
    }

    @Override
    public List<LocalImChatListVo> getLocalImChatList(Long userId, String password, Integer appId, String page, String limit) throws Exception {
        String authToken = loginLocalIm(String.valueOf(userId), password, appId);
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + authToken);
        }
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/chat/message/talk";

        // 构建请求参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (StringUtils.isNotBlank(page)) {
            builder.queryParam("page", page);
        }

        if (StringUtils.isNotBlank(limit)) {
            builder.queryParam("limit", limit);
        }

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.GET,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                // 解析 data 对象
                Object dataObj = response.get("data");
                if (dataObj == null) {
                    return null;
                }
                if (dataObj instanceof ArrayList) {
                    return ((ArrayList<?>) dataObj).stream().map(item -> {
                        LocalImChatListVo localImChatList = new LocalImChatListVo();
                        if (item instanceof Map) {
                            localImChatList.setId((Integer) ((Map) item).get("id"));
                            localImChatList.setUid((Long) ((Map) item).get("uid"));
                            localImChatList.setMode((Integer) ((Map) item).get("mode"));
                            localImChatList.setToUid((Long) ((Map) item).get("to_uid"));
                            localImChatList.setAppId((Integer) ((Map) item).get("app_id"));
                            localImChatList.setCreatedAt((String) ((Map) item).get("created_at"));
                            localImChatList.setUpdatedAt((String) ((Map) item).get("updated_at"));
                        }
                        return localImChatList;
                    }).collect(Collectors.toList());
                } else {
                    throw new Exception("响应数据格式错误：data 不是预期的数组");
                }
            } else {
                throw new Exception("获取会话记录失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }

    @Override
    public List<Map<String, Object>> getLocalImChatHistory(Long userId, String password, Integer appId, Integer toLocalImId, String id) throws Exception {
        String authToken = loginLocalIm(String.valueOf(userId), password, appId);
        // 设置HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        if (authToken != null && !authToken.isEmpty()) {
            headers.set("Authorization", "Bearer " + authToken);
        }
        // 构建请求URL
        String url = localImConfig.getUrl() + "/api/chat/message/records";

        // 构建请求参数
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (toLocalImId != null) {
            builder.queryParam("to_uid", toLocalImId);
        }

        if (StringUtils.isNotBlank(id)) {
            builder.queryParam("id", id);
        }

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        // 发送GET请求
        ResponseEntity<Map> responseEntity = restTemplate.exchange(
                builder.toUriString(),
                HttpMethod.GET,
                requestEntity,
                Map.class
        );

        // 检查响应状态码
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            Map<String, Object> response = responseEntity.getBody();
            if (response != null && Objects.equals(response.get("code"), 200)) {
                // 解析 data 对象
                Object dataObj = response.get("data");
                if (dataObj instanceof java.util.List) {
                    // 处理账号列表
                    return (List<Map<String, Object>>) dataObj;
                } else {
                    throw new Exception("响应数据格式错误：data 不是预期的数组");
                }
            } else {
                throw new Exception("获取会话记录失败：" + (response != null ? response.get("message") : "未知错误"));
            }
        } else {
            throw new Exception("HTTP请求失败，状态码：" + responseEntity.getStatusCodeValue());
        }
    }
}
